<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="应用名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入应用名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['biz:app:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['biz:app:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['biz:app:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['biz:app:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="appList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="图标" align="center" prop="icon" width="70">
        <template slot-scope="scope">
          <img :src="scope.row.icon" alt="" style="width: 50px; height: 50px" />
        </template>
      </el-table-column>
      <el-table-column label="应用名称" align="center" prop="name" />
      <el-table-column label="访问地址" align="center" prop="address" />
      <el-table-column
        label="应用描述"
        align="center"
        prop="description"
        :show-overflow-tooltip="true"
        min-width="180"
      />
      <el-table-column
        label="创建日期"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="190"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleShow(scope.row)"
            v-hasPermi="['biz:app:edit']"
            >详细</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['biz:app:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['biz:app:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应用对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="45%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="应用图标" prop="icon">
          <!--          <el-input v-model="form.icon" placeholder="请输入图标" />-->
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="应用名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入应用名称" />
        </el-form-item>
        <el-form-item label="访问地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入访问地址" />
        </el-form-item>
        <el-form-item label="应用描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item v-if="secret" label="应用appid" prop="appid">
          <el-input
            v-model="form.appid"
            placeholder="请输入应用appid"
            readonly
          />
        </el-form-item>
        <el-form-item v-if="secret" label="应用secret" prop="secret">
          <el-input
            v-model="form.secret"
            placeholder="请输入应用secret"
            readonly
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="!secret">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listApp,
  getApp,
  delApp,
  addApp,
  updateApp,
  exportApp,
} from "@/api/biz/app";
import { validURL, isEmpty } from "../../../utils/validate";

export default {
  name: "App",
  data() {
    const validUrl = (rule, value, callback) => {
      if (!validURL(value)) {
        callback(new Error("请输入正确地址"));
      } else {
        callback();
      }
    };
    const validImg = (rule, value, callback) => {
      if (isEmpty(value)) {
        callback(new Error("请上传图标"));
      } else {
        callback();
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应用表格数据
      appList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        icon: [{ required: true, validator: validImg, trigger: "blur" }],
        name: [
          { required: true, message: "应用名称不能为空", trigger: "blur" },
          { max: 50, message: "长度不能超过50个字符", trigger: "blur" },
        ],
        address: [
          { required: true, message: "访问地址不能为空", trigger: "blur" },
          { max: 255, message: "长度不能超过255个字符", trigger: "blur" },
          {
            required: true,
            validator: validUrl,
            trigger: "blur",
          },
        ],
        description: [
          { required: true, message: "应用描述不能为空", trigger: "blur" },
        ],
      },
      // appid secret控制
      secret: false,
      imageUrl: "",
      uploadUrl: process.env.VUE_APP_BASE_API + "/biz/app/avatar",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询应用列表 */
    getList() {
      this.loading = true;
      listApp(this.queryParams).then((response) => {
        this.appList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        icon: null,
        name: null,
        id: null,
        address: null,
        description: null,
        appid: null,
        secret: null,
        tenantId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.imageUrl = "";
      this.secret = false;
      this.open = true;
      this.title = "添加应用";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.imageUrl = "";
      const id = row.id || this.ids;
      getApp(id).then((response) => {
        this.form = response.data;
        this.imageUrl = this.form.icon;
        this.secret = false;
        this.open = true;
        this.title = "修改应用";
      });
    },
    /** 详细按钮操作 */
    handleShow(row) {
      this.reset();
      this.imageUrl = "";
      const id = row.id || this.ids;
      getApp(id).then((response) => {
        this.form = response.data;
        this.imageUrl = this.form.icon;
        this.secret = true;
        this.open = true;
        this.title = "应用详细";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          //this.form.icon = this.imageUrl;
          if (this.form.id != null) {
            updateApp(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApp(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除应用编号为"' + ids + '"的数据项？')
        .then(function () {
          return delApp(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$modal
        .confirm("是否确认导出所有应用数据项？")
        .then(() => {
          this.exportLoading = true;
          return exportApp(queryParams);
        })
        .then((response) => {
          this.$download.name(response.msg);
          this.exportLoading = false;
        })
        .catch(() => {});
    },
    // 图片上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.icon = res.imgUrl;
    },
    beforeAvatarUpload(file) {
      const noJPG = file.type.indexOf("image/") == -1;
      const isLt1M = file.size / 1024 / 1024 < 1;

      if (noJPG) {
        this.$message.error("只能上传图片格式!");
      }
      if (!isLt1M) {
        this.$message.error("上传图片大小不能超过 1MB!");
      }
      return !noJPG && isLt1M;
    },
  },
};
</script>
<style scoped lang="scss"></style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
